import urllib.request as request
import urllib.parse
import json
import re
import os

# 封装ajax返回一个字典(对象)


def ajax(params):
    url = params['url']
    method = params['method']
    headers = params['header']
    data = urllib.parse.urlencode(params['data']).encode()
    req = request.Request(url=url, headers=headers,
                          method=method, data=data)
    res = request.urlopen(req)
    return res.read().decode('utf8')


def ajax_header(params):
    url = params['url']
    method = params['method']
    headers = params['header']
    data = urllib.parse.urlencode(params['data']).encode()
    req = request.Request(url=url, headers=headers,
                          method=method, data=data)
    res = request.urlopen(req)
    return str(res.headers)


def gethtml(url):
    res = ajax({
        "url": url,
        "method": 'GET',
        "header": {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36',
            'Connection': 'keep-alive',
        },
        "data": {}
    })
    return res


if __name__ == '__main__':
    while True:
        try:
            print('参考地址: https://book.zongheng.com/chapter/1269823/71535692.html')
            url = input('请输入url(回车确定后自动下载):')
            html = gethtml(url)
            title_reg = re.compile(r'title_txtbox.*')
            title = title_reg.findall(html)[0].replace(
                'title_txtbox">', '').replace('</div>', '')
            reg = re.compile(r'acticleBody.*')
            text = reg.findall(html)[0].replace('acticleBody"><p>', ' ').replace(
                '</p>', '\n').replace('<p>', ' ').replace('<div>', '').replace('</div>', '')
            if os.path.exists(f'{title}.txt'):
                print(f'{title}.txt 文件已存在')
                continue
            with open(f'{title}.txt', 'w+', encoding='utf8') as file:
                file.write(title+'\n'+text)
        except:
            print('程序异常')
        finally:
            print('请重试')
